package com.github.beansoft.jadx.gui.idea;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.vfs.VirtualFile;
import jadx.gui.JadxGUI;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
 @author beansoft
 @date 2021-05-01
 */
public class OpenJadxContextAction extends AnAction {
    private static final List<String> exts = Arrays.asList("apk", "dex", "jar", "class", "smali", "zip", "aar", "arsc");
    public void actionPerformed(AnActionEvent e) {
        VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
        if(!isAllowedFile(virtualFile)) {
            return;
        }

        JadxGUI.main(new String[] {virtualFile.getCanonicalPath()});
    }

    boolean isAllowedFile(VirtualFile virtualFile) {
        if (virtualFile == null) {
            return false;
        }
        String name = virtualFile.getName();
        if(StringUtils.isEmpty(name)) {
            return false;
        }
        String ext = FileUtilRt.getExtension(name);
        if(StringUtils.isEmpty(ext)) {
            return false;
        }
        return exts.contains(ext.toLowerCase());
    }

    public void update(@NotNull AnActionEvent e) {
        Presentation presentation = e.getPresentation();
        VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);

        presentation.setEnabledAndVisible(isAllowedFile(virtualFile));
    }

    // Always available and enabled
    @Override
    public boolean isDumbAware() {
        return true;
    }
}